package com.ra.util;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;
import org.xhtmlrenderer.util.FSImageWriter;

import com.espirit.weixin.core.WeixinUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.googlecode.cswish.exception.ApplicationException;
import com.opensymphony.xwork2.Result;

@Service
public class QRCodeService {

	private static final Log logger = LogFactory.getLog(QRCodeService.class);

	@Resource
	private WeixinUtil weixinUtil;
	
	public Result show(String info, int width, int height) throws Exception {
		// TODO: 针对info, 引入缓存机制, 同一天内, 相同info不重复生成 (注:原因是微信对临时二维码的调用有每天100万次的限制)
		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.reset();
		OutputStream outputStream = response.getOutputStream();

		genereateQRCode(outputStream, info, null, width, height);

		outputStream.close();
		return null;
	}
	
	public void genereateQRCode(OutputStream outputStream, String info, String logo,
			int width, int height) {
		if (width <= 0 || width >= 3000) {
			width = 3000;
		}
		if (height <= 0 || height >= 3000) {
			height = 3000;
		}

		if (logo == null) {
			logo = "/logo.jpg";
		}
		InputStream input = this.getClass().getResourceAsStream(logo);
		encode(info, width, height, input, outputStream);
		IOUtils.closeQuietly(input);
	}

	private void encode(String content, int width, int height,
			InputStream srcImagePath, OutputStream destImagePath) {
		try {
			if (content == null || content.isEmpty()) {
				throw new ApplicationException("二维码内容不可以为空");
			}
			
			FSImageWriter imageWriter = FSImageWriter.newJpegWriter(1f);
			BufferedImage img = genBarcode(content, width, height, srcImagePath);
			imageWriter.write(img, destImagePath);
		} catch (Exception ex) {
			logger.error("Failed to generate QR code", ex);
		}
	}

	private BufferedImage genBarcode(String content, int width, int height,
			InputStream srcImageStream) throws WriterException, IOException {
		// FIXME: 自动缩放logo图
		int IMAGE_WIDTH = 30;
		int IMAGE_HEIGHT = 30;
		int IMAGE_HALF_WIDTH = IMAGE_WIDTH / 2;
		int FRAME_WIDTH = 2;

		int[][] srcPixels = new int[IMAGE_WIDTH][IMAGE_HEIGHT];
		// 读取源图像
		if (srcImageStream != null) {
			BufferedImage scaleImage = scale(srcImageStream, IMAGE_WIDTH,
					IMAGE_HEIGHT, true);
			for (int i = 0; i < scaleImage.getWidth(); i++) {
				for (int j = 0; j < scaleImage.getHeight(); j++) {
					srcPixels[i][j] = scaleImage.getRGB(i, j);
				}
			}
		}

		Map<EncodeHintType, Object> hint = new HashMap<EncodeHintType, Object>();
		hint.put(EncodeHintType.CHARACTER_SET, "utf-8");
		hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

		// 生成二维码
		MultiFormatWriter mutiWriter = new MultiFormatWriter();
		BitMatrix matrix = mutiWriter.encode(content, BarcodeFormat.QR_CODE,
				width, height, hint);

		// 二维矩阵转为一维像素数组
		int halfW = matrix.getWidth() / 2;
		int halfH = matrix.getHeight() / 2;
		int[] pixels = new int[width * height];

		for (int y = 0; y < matrix.getHeight(); y++) {
			for (int x = 0; x < matrix.getWidth(); x++) {
				// 读取图片
				if (x > halfW - IMAGE_HALF_WIDTH
						&& x < halfW + IMAGE_HALF_WIDTH
						&& y > halfH - IMAGE_HALF_WIDTH
						&& y < halfH + IMAGE_HALF_WIDTH) {
					pixels[y * width + x] = srcPixels[x - halfW
							+ IMAGE_HALF_WIDTH][y - halfH + IMAGE_HALF_WIDTH];
				}
				// 在图片四周形成边框
				else if ((x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH
						&& x < halfW - IMAGE_HALF_WIDTH + FRAME_WIDTH
						&& y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH
						+ IMAGE_HALF_WIDTH + FRAME_WIDTH)
						|| (x > halfW + IMAGE_HALF_WIDTH - FRAME_WIDTH
								&& x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
								&& y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH
								+ IMAGE_HALF_WIDTH + FRAME_WIDTH)
						|| (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH
								&& x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
								&& y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH
								- IMAGE_HALF_WIDTH + FRAME_WIDTH)
						|| (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH
								&& x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
								&& y > halfH + IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH
								+ IMAGE_HALF_WIDTH + FRAME_WIDTH)) {
					pixels[y * width + x] = 0xfffffff;
				} else {
					// 此处可以修改二维码的颜色，可以分别制定二维码和背景的颜色；
					pixels[y * width + x] = matrix.get(x, y) ? 0xff000000
							: 0xfffffff;
				}
			}
		}

		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		image.getRaster().setDataElements(0, 0, width, height, pixels);

		return image;
	}

	/**
	 * 把传入的原始图像按高度和宽度进行缩放，生成符合要求的图标
	 * 
	 * @param srcImageFile
	 *            源文件地址
	 * @param height
	 *            目标高度
	 * @param width
	 *            目标宽度
	 * @param hasFiller
	 *            比例不对时是否需要补白：true为补白; false为不补白;
	 * @throws IOException
	 */
	private static BufferedImage scale(InputStream srcImageFile, int height,
			int width, boolean hasFiller) throws IOException {
		double ratio = 0.0; // 缩放比例
		BufferedImage srcImage = ImageIO.read(srcImageFile);
		Image destImage = srcImage.getScaledInstance(width, height,
				BufferedImage.SCALE_SMOOTH);
		// 计算比例
		if ((srcImage.getHeight() > height) || (srcImage.getWidth() > width)) {
			if (srcImage.getHeight() > srcImage.getWidth()) {
				ratio = (new Integer(height)).doubleValue()
						/ srcImage.getHeight();
			} else {
				ratio = (new Integer(width)).doubleValue()
						/ srcImage.getWidth();
			}
			AffineTransformOp op = new AffineTransformOp(
					AffineTransform.getScaleInstance(ratio, ratio), null);
			destImage = op.filter(srcImage, null);
		}
		if (hasFiller) {// 补白
			BufferedImage image = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_RGB);
			Graphics2D graphic = image.createGraphics();
			graphic.setColor(Color.white);
			graphic.fillRect(0, 0, width, height);
			if (width == destImage.getWidth(null))
				graphic.drawImage(destImage, 0,
						(height - destImage.getHeight(null)) / 2,
						destImage.getWidth(null), destImage.getHeight(null),
						Color.white, null);
			else
				graphic.drawImage(destImage,
						(width - destImage.getWidth(null)) / 2, 0,
						destImage.getWidth(null), destImage.getHeight(null),
						Color.white, null);
			graphic.dispose();
			destImage = image;
		}
		return (BufferedImage) destImage;
	}

	public static void main(String[] args) {
		try {
			InputStream input = QRCodeService.class.getResourceAsStream("/logo.jpg");
			new QRCodeService().encode("http://www.sina.com.cn/", 300, 300,
					input, new FileOutputStream(new File("d:\\abc-2.jpg")));
			IOUtils.closeQuietly(input);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}